import {
  AfterViewInit,
  ChangeDetectionStrategy,
  Component,
  ElementRef,
  Input,
  OnDestroy,
  OnInit,
  QueryList,
  Renderer2,
  ViewChild,
  ViewChildren,
} from '@angular/core';

export interface ImageSlider {
  id: number;
  imgUrl: string;
  link: string;
  caption: string;
}

@Component({
  selector: 'app-image-slider',
  templateUrl: './image-slider.component.html',
  styleUrls: ['./image-slider.component.css'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ImageSliderComponent implements OnInit, AfterViewInit, OnDestroy {
  @Input() sliders: ImageSlider[];
  @Input() sliderHeight = '117px';
  @Input() intervalBySeconds = 2;

  @ViewChild('imageSlide', { static: true }) imgSlider: ElementRef;
  @ViewChildren('img') imgs: QueryList<ElementRef>;

  selectedIndex = 0;
  intervalId;

  constructor(private rd2: Renderer2) {}

  ngOnInit(): void {}

  ngAfterViewInit(): void {
    if (this.intervalBySeconds <= 0) {
      return;
    }
    this.intervalId = setInterval(() => {
      this.rd2.setProperty(
        this.imgSlider.nativeElement,
        'scrollLeft',
        ((this.getIndex(++this.selectedIndex) % this.sliders.length) *
          this.imgSlider.nativeElement.scrollWidth) /
          this.sliders.length
      );
    }, this.intervalBySeconds * 1000);
  }

  ngOnDestroy(): void {
    clearInterval(this.intervalId);
  }
  getIndex(idx: number): number {
    return idx >= 0
      ? idx % this.sliders.length
      : (this.sliders.length - Math.abs(idx)) % this.sliders.length;
  }

  handleScroll(ev): void {
    const ratio =
      (ev.target.scrollLeft * this.sliders.length) / ev.target.scrollWidth;

    this.selectedIndex = Math.round(ratio);
  }
}
